import { Inject, Get, Query, SetHeader, Post, Body } from '@midwayjs/core';
import { CoolController, BaseController, CoolUrlTag, TagTypes } from '@cool-midway/core';
import { StudentStudentEntity } from '../../entity/student';
import { StudentStudentService } from '../../service/student';
import { BaseSysUserEntity } from '../../../base/entity/sys/user';
import { StudentWechatService } from '../../service/wechat';


/**
 * 学生信息
 */
@CoolUrlTag({
  key: TagTypes.IGNORE_TOKEN,
  value: ['getSalesQrCode', 'getPersonalQrCode', 'getPhoneNumber', 'getOpenid', 'loginByOpenidGetStudentList', 'getLatestAppointment', 'getWechatConfig']
})
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: StudentStudentEntity,
  service: StudentStudentService,
  pageQueryOp: {
    keyWordLikeFields: ['a.name', 'a.phone', 'a.studentNo'],
    fieldEq: ['a.sales', 'a.shop'],
    where: async ctx => {
      const { source, inGroup, project, phone, name, shopId, train } = ctx.request.body;
      const where = [];

      if (shopId) {
        where.push([
          'a.shop = :shopId',
          { shopId }
        ]);
      }

      if (source) {
        where.push([
          'a.source = :source',
          { source }
        ]);
      }

      if (inGroup) {
        where.push([
          'a.inGroup = :inGroup',
          { inGroup }
        ]);
      }

      if (project) {
        where.push([
          'a.project = :project',
          { project }
        ]);
      }

      if (phone) {
        where.push([
          'a.phone = :phone',
          { phone }
        ]);
      }

      if (name) {
        where.push([
          'a.name = :name',
          { name }
        ]);
      }

      if (train) {
        if (train == 1) {
          where.push([
            // '(a.trainCount > :minTrainCount OR a.giftCount > :minGiftCount)',
            'a.buyCount > :buyCount',
            { buyCount: 0 }
            // { minTrainCount: 0, minGiftCount: 0 }
          ]);
        }

        if (train == 2) {
          where.push([
            'a.trainCount = :trainCount AND a.giftCount = :giftCount',
            { trainCount: 0, giftCount: 0 }
          ]);
        }
      }

      return where;
    },
    join: [
      {
        entity: BaseSysUserEntity,
        alias: 'c',
        condition: 'a.sales = c.id',
        type: 'leftJoin',
      }
    ],
    select: [
      'a.*', 
      'c.name as salesName',
    ],
    addOrderBy: {
      'a.createTime': 'DESC',
    },
  },
})
export class AdminStudentStudentController extends BaseController {
  @Inject()
  studentStudentService: StudentStudentService;

  @Inject()
  studentWechatService: StudentWechatService;

  /**
   * 获取销售二维码
   */
  @Get('/getSalesQrCode')
  @SetHeader('Access-Control-Allow-Origin', '*')
  @SetHeader('Access-Control-Allow-Methods', 'GET')
  async getSalesQrCode(@Query('studentId') studentId: number) {
    return this.ok(await this.studentStudentService.getSalesQrCode(studentId));
  }

  /**
   * 获取个人信息二维码
   */
  @Get('/getPersonalQrCode')
  @SetHeader('Access-Control-Allow-Origin', '*')
  @SetHeader('Access-Control-Allow-Methods', 'GET')
  async getPersonalQrCode(@Query('studentId') studentId: number) {
    return this.ok(await this.studentStudentService.getPersonalQrCode(studentId));
  }

  @Get('/getLatestAppointment')
  async getLatestAppointment(@Query('studentId') studentId: number) {
    return this.ok(await this.studentStudentService.getLatestAppointment(studentId));
  }

  /**
   * 微信根据code获取手机号
   */
  @Post('/getPhoneNumber')
  async getPhoneNumber(@Body('code') code: string, @Body('openid') openid: string) {
    return this.ok(await this.studentWechatService.getPhoneNumber(code, openid));
  }

  /**
   * 手机号返回学员列表
   */
  @Post('/getStudentByPhone')
  async getStudentByPhone(@Body('phone') phone: string) {
    return this.ok(await this.studentStudentService.getStudentByPhone(phone));
  }

  /**
   * 获取小程序用户的openid
   */
  @Get('/getOpenid')
  async getOpenid(@Query('code') code: string) {
    return this.ok(await this.studentWechatService.getOpenid(code));
  }

  /**
   * 根据小程序的openid获取用户列表
   */
  @Post('/loginByOpenidGetStudentList')
  async loginByOpenidGetStudentList(@Body('openid') openid: string) {
    return this.ok(await this.studentWechatService.loginByOpenidGetStudentList(openid));
  }

  /**
   * 获取小程序配置
   */
  @Get('/getWechatConfig')
  async getWechatConfig() {
    return this.ok(await this.studentWechatService.getWechatConfig());
  }
}
